threadCnt = 0 #已经有的线程数
maxThreadCnt = 10 #最大线程数
ips = [] #被检测的IP
ipMap = {} #id=>ipInfo
sep = 'MySep' #url中用来做分隔符
timer = 0
lastMinute = [] #最近一分钟点击数
###
获取IP
###
getIpComplete=true
getIp = ->
	unless getIpComplete
		#只允许一个进程执行
		return off
	getIpComplete = off
	ajaxSetting =
		data:
			limit:300
		dataType:'json'
		timeout:10000
		complete:->
			getIpComplete = true
		error:getIp
		success:(data)->
			if data and data.length >1 #最后一个检测结果不上报，导致无限循环。所以大于1的时候才检测
				ips = ips.concat data
				#转化为map
				for v in data
					ipMap[v.agt_id] = v
				setProxy()
			else
				showEnd()
		async:off
	$.ajax "#{serverUrlPre}Check/getIp4check",ajaxSetting

###
展示结果
###
showEnd = ->
	if timer
		clearTimeout timer
	notification = webkitNotifications.createNotification 'images/notification.png','活已经干完了','我要休息20分钟'
	notification.show()
	notification.onclick = ->
		notification.close()
	timer = setTimeout ->
		notification.close()
		getIp()
	,1200 * 1000

###
发起一个请求
###
createThread = ->
	data = ips.shift()
	if data
		threadCnt++
		respPre = "#{serverUrlPre}Check/setRank/agt_id/#{data.agt_id}/"
		handler =
			dataType:'json'
			timeout:16000
			#async:off
			complete:->
				threadCnt--
				delete ipMap[data.agt_id]
				showStasticsInfo()
				createThreads()
			error:->
				#上报错误
				$.get "#{respPre}agt_err/1",->
					stastics.err++
					showCheckProxy data,off
			success:(rank)->
				$.get "#{respPre}agt_rank/#{rank}",->
					stastics[rank]++
					lastMinute.push(+ new Date())
					showCheckProxy data,on
		$.ajax "http://visitweb.sinaapp.com?s=#{sep}#{data.agt_id}#{sep}",handler
		return on
	else if 0==threadCnt
		getIp()
	off
###
#创建线程
###
createThreads = ->
	leftThread = ->
		maxThreadCnt = Math.max($('#maxThread').val(),2)
		maxThreadCnt - threadCnt
	canHttp = ->
		now = + new Date()
		lastMinute = lastMinute.filter (v)->
			#1分钟内的请求数
			return now - v < 60 * 1000
		return lastMinute.length < 130
	while leftThread() > 0 and canHttp()
		unless createThread()
			break

###
#设置代理
###
setProxy = ->
	###
	设置代理
	###
	#代理函数
	proxyFn = """
		function FindProxyForURL(url, host) {
			if (host == 'visitweb.allalla.com' || 'ip.taobao.com'==host){
				return 'DIRECT';
			}else{
				var ipMap = #{JSON.stringify(ipMap)};
				var id = url.split('#{sep}')[1];
				if(id){
					var info = ipMap[id];
					return 'PROXY ' + info['agt_ip'] + ':' + info['agt_port'];
				}else{
					return 'PROXY 1.1.1.1:80';
				}
			}
			return 'DIRECT';
		}
	"""
	proxyConfig =
		mode: "pac_script"
		pacScript:
			data:proxyFn.trim()
			mandatory :on
	chrome.proxy.settings.set {value:proxyConfig,scope:'regular'},createThreads

###
#界面
###
$('#form').submit ->
	if timer
		clearTimeout timer
	if threadCnt
		alert '正在测试'
	else
		getIp()
	off
if location.search.match(/(\?|&)rank=1(&|$)/)
	getIp()
###
#界面展示
###
#统计结果
stastics=
	0:0
	1:0
	2:0
	3:0
	4:0
	5:0
	6:0
	7:0
	err:0
	alive:0
	'':0
rankStartTime = new Date().getTime() #开始时间
#展示验证结果
showCheckProxy = (oneProxy,success=on)->
	oneProxy.agt_lasttime = new Date(oneProxy.agt_lasttime*1000).toLocaleDateString()
	className = if success then 'success' else 'error'
	html = "<li class='#{className}'>#{oneProxy.agt_lasttime} rank:#{oneProxy.agt_rank.big()} err:#{oneProxy.agt_err.big()}</li>"
	$('#checkResult').append $(html)
	#document.body.scrollTop +=20
#剩余个数
checkLeft = undefined
getCheckLeft = ->
	if undefined == checkLeft
		$.getJSON "#{serverUrlPre}Check/getIp4checkCnt",(cnt)->
			checkLeft = cnt
	checkLeft
#展示统计信息
showStasticsInfo = ->
	usedTime = new Date().getTime() - rankStartTime
	html = ''
	checkCnt = 0
	for k,v of stastics
		unless v
			continue
		html += " <li>#{k}:#{v}</li>"
		checkCnt += v
	html += "<li>time used:#{Math.round(usedTime/1000)}s</li>"
	if getCheckLeft() != undefined
		html += "<li>process: #{checkCnt}/#{checkLeft}</li>"
	$('#stastics').html html

###
#test
###
#$.get = (data)->
	#console.log data
